package com.bianmaba.utils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.SerializationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.nio.charset.Charset;

/**
 * 序列化工具类
 *
 * @author cWX183898
 */
public final class SerializationUtil {
    public static final Logger LOG = LoggerFactory.getLogger(SerializationUtil.class);

    private SerializationUtil() {
    }

    public static boolean serializeToFile(Object obj, String path) {
        String data = serialize(obj);
        if (data != null) {
            try {
                FileUtils.writeStringToFile(new File(path),
                        data,
                        Charset.defaultCharset().name(),
                        false);
                return true;
            } catch (IOException e) {
                LOG.debug("写序列化数据到文件出现异常.", e);
            }
        }
        return false;
    }

    /**
     * 将指定的对应序列化成一个字符串
     *
     * @param obj 需要序列化的对象
     * @return 序列化后的字符串, 如果出现异常则返回null
     */
    public static String serialize(Object obj) {
        String data = null;
        if (obj != null) {
            try {
                byte[] byteArr =
                        SerializationUtils.serialize((Serializable) obj);
                byte[] bytes = Base64Util.encode(byteArr, 0);
                data = new String(bytes, Charset.defaultCharset());
            } catch (Exception e) {
                LOG.debug("序列化对象出现异常.", e);
            }
        }
        return data;
    }

    public static Object deserializeFromFile(String path) {
        try {
            String data =
                    FileUtils.readFileToString(new File(path),
                            Charset.defaultCharset().name());
            return deserialize(data);
        } catch (IOException e) {

            LOG.debug("读取序列化文件出现异常.", e);
        }
        return null;
    }

    /**
     * 将字符串反序列化成一个对你
     *
     * @param data 字符串
     * @return 反序列化后的对象, 如果出现异常则返回null
     */
    public static Object deserialize(String data) {
        Object obj = null;
        try {
            if (data == null) {
                return null;
            }

            byte[] bytes = Base64Util.decode(data);
            obj = SerializationUtils.deserialize(bytes);
        } catch (Exception e) {
            LOG.error("反序列化数据时出现异常.", e);
        }
        return obj;
    }
}
